﻿namespace FileTransferDesktop.ViewModels.Dialogs;

[ObservableRecipient]
public partial class DownloadDialogViewModel : ObservableObject
{
    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(Dialogs.DownloadDialogViewModel.ConfirmCommand))]
    private string _digit1 = string.Empty;

    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(Dialogs.DownloadDialogViewModel.ConfirmCommand))]
    private string _digit2 = string.Empty;

    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(Dialogs.DownloadDialogViewModel.ConfirmCommand))]
    private string _digit3 = string.Empty;

    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(Dialogs.DownloadDialogViewModel.ConfirmCommand))]
    private string _digit4 = string.Empty;

    private void ForceUpper(Action<string> setProp, string value)
    {
        if (value.ToUpperInvariant() != value)
            setProp(value.ToUpperInvariant());
    }

    partial void OnDigit1Changed(string value) => ForceUpper(x => Digit1 = x, value);

    partial void OnDigit2Changed(string value) => ForceUpper(x => Digit2 = x, value);

    partial void OnDigit3Changed(string value) => ForceUpper(x => Digit3 = x, value);

    partial void OnDigit4Changed(string value) => ForceUpper(x => Digit4 = x, value);

    public Action<string>? OnConfirmCode { get; set; }
    public string Code => $"{Digit1}{Digit2}{Digit3}{Digit4}";

    public event EventHandler<bool>? RequestClose;
    public bool ConfirmButtonCanExecute => Code.Length == 4;

    [RelayCommand(CanExecute = nameof(ConfirmButtonCanExecute))]
    private void Confirm()
    {
        OnConfirmCode?.Invoke(Code);
        RequestClose?.Invoke(this, true);
    }
}
